package com.gongj.gateway;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.Instant;
import java.util.concurrent.TimeUnit;

/**
 * 统计某个或者某种路由的处理时长
 */
public class CustomGatewayFilter implements GatewayFilter, Ordered {
    private static final Logger log = LoggerFactory
            .getLogger( CustomGatewayFilter.class );
    private static final String COUNT_START_TIME = "countStartTime";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //得到当前时间
        Instant now = Instant.now();
        //Instant.now()使用的是UTC时间,会与北京时间相差八小时
        now.plusMillis(TimeUnit.HOURS.toMillis(8));
        //now.toEpochMilli()  毫秒数
        exchange.getAttributes().put(COUNT_START_TIME, now.toEpochMilli());
        return chain.filter(exchange).then(
                Mono.fromRunnable(()->{
                    long startTime = exchange.getAttribute(COUNT_START_TIME);
                    long endTime = (Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8)).toEpochMilli() - startTime);
                    log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                })
        );
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
